class Mobile::ChatsController < MobileController
  def index
    @shop = Shop.find params[:shop_id]
    @user = load_current_user(params[:token])
    @shop_chat = ShopChat.find_or_create_by(shop_id: @shop.id, user_id: @user.id)
    @chat_windows = ChatWindow.where(
      shop_chat_id: @shop_chat.id,
      user_id: @user.id
    ).order("updated_at DESC")
    if @chat_windows.count <= 0
      @chat_window = ChatWindow.create(
        shop_chat_id: @shop_chat.id,
        user_id: @user.id,
        shoper_id: @shop.shopers.order('RAND()').first.id
      )
    else
      @chat_window = @chat_windows.first
    end
  end

  def create
    @chat_message = ChatMessage.new(
      chat_window_id: params[:chat_window_id],
      messageable_id: params[:messageable_id],
      messageable_type: params[:messageable_type],
      content: params[:content]
    )
    if @chat_message.save
      redirect_to mobile_chats_path(shop_id: @chat_message.chat_window.shoper.shop.id, token: params[:token])
    else
      redirect_to mobile_chats_path(shop_id: @chat_message.chat_window.shoper.shop.id, token: params[:token])
    end
  end
  
end
